<?php


namespace app\api\controller;

use app\common\controller\BaseController;
use hg\apidoc\annotation as Apidoc;
use Qcloud\Cos\Exception\ServiceResponseException;
use think\facade\Db;
use Qcloud\Cos\Client;

/**
 * @Apidoc\Title("首页")
 * @Apidoc\Group("index")
 * @Apidoc\Sort("100")
 */
class Index extends BaseController
{
    /**
     * @Apidoc\Title("首页")
     * @Apidoc\NotHeaders()
     * @Apidoc\NotQuerys()
     * @Apidoc\NotParams()
     */
    public function index()
    {
        $id   = $this->param('id/s', '');
        if(empty($id)){
            return error('参数错误');
        }
        $status   = $this->param('status/s', '');
        $outputUrl   = $this->param('outputUrl/s', '');

        if($status == "COMPLETED"){

            // 下载远程文件到本地临时文件
            $tempFilePath = tempnam(sys_get_temp_dir(), 'cos_upload');
            file_put_contents($tempFilePath, file_get_contents(stripslashes($outputUrl)));

            // 腾讯云 COS 配置
            $secretId = "AKIDINN7sOhgtseAPPQIQIlz9ERYaP3CFKEw"; // 替换为你的 SecretId
            $secretKey = "XoqaBVjiS0kEZfVHoCYeU4VyFE0eEY6O"; // 替换为你的 SecretKey
            $region = "ap-guangzhou"; // 替换为你的 COS 区域，例如 ap-guangzhou
            $bucket = "ai-dev-1305433883"; // 替换为你的存储桶名称

            $cosClient = new Client(
                array(
                    'region' => $region,
                    'credentials' => array(
                        'secretId' => $secretId,
                        'secretKey' => $secretKey
                    )
                )
            );


            $path = rand(1, 10000000) . '_' . date('YmdHis') . basename(parse_url($outputUrl, PHP_URL_PATH));

            try {
                // 上传视频文件到腾讯云 COS
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $path, // 文件名
                    'Body' => fopen($tempFilePath, 'rb') // 文件内容
                ));


            } catch (ServiceResponseException|\Exception $e) {
                // 请求失败
                unlink($tempFilePath);
                return error('上传文件失败: ' . $e->getMessage());
            } finally {
                // 删除临时文件
                unlink($tempFilePath);
            }
            $modifiedString = str_replace(".mp4", "_0.jpg", $path);

            $data = [
                'status' => 1,
                'cover' => stripslashes("https://" . $bucket . ".cos." . $region . ".myqcloud.com/" . $modifiedString),
                'url' => stripslashes("https://" . $bucket . ".cos." . $region . ".myqcloud.com/" . $path),
            ];

        } else {
            $data = [
                'status' => 4,
            ];
        }
        Db::name("ai_video")->where('task_id', $id)->update($data);
        $msg  = 'ok';
        return success($msg);
    }
}